package com.sqliteair.data
{	
	import flash.data.SQLConnection;
	import flash.data.SQLResult;
	import flash.data.SQLStatement;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	import flash.filesystem.File;
	
	import mx.controls.Alert;
	
	public class Database extends EventDispatcher
	{
		private var database:File = new File();
		private var conn:SQLConnection = new SQLConnection();
		private var statement:SQLStatement = new SQLStatement();
		private var result:SQLResult = new SQLResult();
		
		public function Database(){}
		
		public function CreateDatabase(db:File):void
		{
			this.database = db;
			if(database != null)
			{
				this.conn = new SQLConnection();
				this.conn.open(this.database,false);
				trace("Database Created");
				this.conn.addEventListener(SQLEvent.OPEN,dbOpenHandler);
				this.conn.addEventListener(SQLErrorEvent.ERROR,dbErorrHandler);
			}
			else
			{
				Alert.show("Null of the Database file.");
			}
		}
		
		public  function CloseDatabase():void
		{
			this.conn.close();
			trace("Database Closed");
			this.conn.clean();
		}
		
		public function ExcuteNonQuery(sql:String):void
		{		
			this.statement.sqlConnection = this.conn;
			this.statement.text = sql;
			this.statement.execute();
			trace("Do function ExcuteNonQuery");
			
			this.statement.addEventListener(SQLEvent.RESULT,resultHandler);
			this.statement.addEventListener(SQLErrorEvent.ERROR,dbErorrHandler);
			
		}
		
		public function ExcuteQuery(sql:String):void
		{			
			this.statement.sqlConnection = this.conn;
			this.statement.text = sql;
			this.statement.execute();
			trace("Do function ExcuteResult");
			
			this.statement.addEventListener(SQLEvent.RESULT,resultHandler);
			this.statement.addEventListener(SQLErrorEvent.ERROR,dbErorrHandler);
			
		}
		
		public function GetResult():SQLResult
		{
			trace("Do function GetResult");
			return this.result;
		}
		
		private function dbOpenHandler(evnet:SQLEvent):void
		{
			trace("Dispatch DBOPENED Event");
			this.dispatchEvent(new Event("DBOPENED"));
		}
		
		private function resultHandler(event:SQLEvent):void
		{
			this.result = this.statement.getResult();
			trace("Dispatch GETRESULT Event");
			this.dispatchEvent(new Event("GETRESULT"));
		}
		
		private function dbErorrHandler(event:SQLErrorEvent):void
		{
			Alert.show(event.error.message,"SQL Error");
			trace(event.error.message);
		}
	}
}